/*
 * XMLDocumentFactory.java
 *
 * Created on July 28, 2007, 9:40 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package com.afaker.rss.xml;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;
import org.xml.sax.InputSource;

/**
 *
 * @author bruce
 */
public class XMLDocumentFactory {
    
    /**
     * Creates a new instance of XMLDocumentFactory
     */
    private SAXBuilder builder=new SAXBuilder();
    private Document doc = null;
    
    
    public XMLDocumentFactory() {
    }
    
    public XMLDocumentFactory(InputSource input) {
        
    }
    
    public Document build(String url) {
        try {            
            doc=builder.build(new File(url));
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        } catch (JDOMException ex) {
            ex.printStackTrace();
            return null;
        }
        return doc;
    }
    
    public void outputToFile(String url) {
        outputToFile(doc,url);
    }
    
    public static boolean outputToFile(Document document,String url) {
        XMLOutputter dog=new XMLOutputter();
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(url);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
            return false;
        }
        try {
            dog.output(document,output);
            output.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
            return false;
        }
        
        try {
            output.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return true;
    }
    
    public Element getRootElement() {
        return doc.getRootElement();
    }
}
